package com.ramos.kuaixiao.driver.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.BuildConfig;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.network.DownloadUpdateFileTask;
import com.ramos.kuaixiao.shops.ui.MallUserFragment;
import com.ramos.kuaixiao.ui.BaseActivity;
import com.ramos.kuaixiao.utils.AppManager;
import com.ramos.kuaixiao.utils.DownloadImageTask;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StartLocation;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.util.TimerTask;
import java.util.concurrent.Executors;

public class DriverMainActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "DriverMainActivity";
    // 定义FragmentManager对象管理器
    private FragmentManager fragmentManager;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_my;
    private DriverOrderFragment mMallOrderFragment;
    private MallUserFragment mMallUserFragment;

    private TextView tv_home_order;
    private TextView tv_home_my;
    private ImageView ib_home_order;
    private ImageView ib_home_my;
    private long exitTime = 0;
    private long mExitTime;
    StartLocation startLocation;
    private LocationManager lm;//【位置管理】
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkGPS();
        startLocation = new StartLocation(this);
        startLocation.startLocation();
        setContentView(R.layout.activity_order_main);
        initView();
        getPermission();
    }

    private void getPermission() {
         if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ) {
            //就跳到让用户选择是否授权  给个码走返回方法
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA
                            ,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
        }
    }

    private void checkGPS() {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，申请权限。
                //Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();

            } else {
                // 有权限了，去放肆吧。
                // Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
            }
        } else {
            //Toast.makeText(getActivity(), "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
            ToastUtils.show("系统检测到未开启GPS定位服务");
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 1315);
        }
    }

    //当我申请权限的时候,调用
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //如果用户选择了同意授权     走我的方法
        if (requestCode == 1001) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                ToastUtils.show("权限拒绝");
            }
        }
    }


    private void initView() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title_mall), false);
        fragmentManager = getSupportFragmentManager();
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_order.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        showOrder();
        new DownloadImageTask().execute();

        getCustomerId();
        if (!BuildConfig.DEBUG) {
            //Utils.executeFixedRate(new ApkUpdateTask(), 1000 * 60, 1000 * 60 * 2);
        }
    }

    public class ApkUpdateTask extends TimerTask {

        public ApkUpdateTask() {

        }

        public void run() {
            if (Utils.isNetworkConnected(App.mContext)) {
                //库存更新
                if (!BuildConfig.DEBUG) {
                    //应用更新检测
                    if (App.mIsUpdate) {
                        DownloadUpdateFileTask product12 = new DownloadUpdateFileTask(DriverMainActivity.this, 2);
                        product12.executeOnExecutor(Executors.newCachedThreadPool());
                    }
                }
            }
        }
    }

    private void getCustomerId() {
        try {
            String url = NetUtils.FIND_UID;
            String path = url + SharedPreference.getPreferString("id");
            Log.d(TAG, "path:" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            org.json.JSONObject jsonObejct = user.getJSONObject("data");
                            SharedPreference.setPreferString("customerId", jsonObejct.getString("id"));
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {

                }
            });
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        startLocation.stotLocation();
        new ApkUpdateTask().cancel();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_home_order:
                showOrder();
                break;
            case R.id.re_home_my:
                showMy();
                break;
            default:
                break;
        }
    }


    private void showMy() {

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts_clk_mall);
        tv_home_my.setTextColor(getResources().getColor(R.color.title_mall));

        showFragment("My");
    }


    private void showOrder() {

        ib_home_order.setImageResource(R.drawable.tab_schedule_clk_mall);
        tv_home_order.setTextColor(getResources().getColor(R.color.title_mall));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        showFragment("Order");
    }

    private void showFragment(String paramString) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragments(fragmentTransaction);
        switch (paramString) {
            case "Order":
                // 如果fg2为空，则创建一个并添加到界面上
                if (mMallOrderFragment == null) {
                    mMallOrderFragment = new DriverOrderFragment();
                    fragmentTransaction.add(R.id.fragment_container, mMallOrderFragment);
                } else {
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mMallOrderFragment);
                }
                break;

            case "My":
                // 如果fg4为空，则创建一个并添加到界面上
                if (mMallUserFragment == null) {
                    mMallUserFragment = new MallUserFragment();
                    fragmentTransaction.add(R.id.fragment_container, mMallUserFragment);
                } else {
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mMallUserFragment);
                }
                break;
        }
        fragmentTransaction.commit(); // 提交
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        if (mMallOrderFragment != null) {
            fragmentTransaction.hide(mMallOrderFragment);
        }
        if (mMallUserFragment != null) {
            fragmentTransaction.hide(mMallUserFragment);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(DriverMainActivity.this, "再按一次返回将退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }
}
